package com.shangxia.study.juc.lock.aqs;

import java.util.concurrent.CountDownLatch;

/**
 * @author zhouya38158
 * @Package com.shangxia.study.juc.lock.aqs
 * @date 2021/10/29 17:36
 */
public class MyReentrantLockTest {
    static Integer NUM = 0;
    static Integer NUM_SAFE = 0;
    static MyReentrantLock myLock = new MyReentrantLock();

    public static void main(String[] args) {
        MyReentrantLockTest test = new MyReentrantLockTest();
        test.add();
        test.addSafe();
        System.out.println("NUM=" + NUM);
        System.out.println("NUM_SAFE=" + NUM_SAFE);
    }

    public void add() {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                for (int j = 0; j < 3000; j++) {
                    NUM++;
                }
                countDownLatch.countDown();
            }, "test_NUM" + i).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void addSafe() {
        CountDownLatch countDownLatch = new CountDownLatch(5);

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                myLock.lock();
                try {
                    addS();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    myLock.unLock();
                }
                countDownLatch.countDown();
            }, "test_NUM_SAFE" + i).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void addS(){
        myLock.lock();
        try {
            for (int j = 0; j < 3000; j++) {
                NUM_SAFE++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            myLock.unLock();
        }
    }
}
